import qs from "qs";
import cookie from "js-cookie";
import * as VueRouter from "vue-router";
import api from "/@//api";
import Router from "/@//views/router.vue";

const routes = [{
    name: 'index',
    path: '/',
    component: () => import('/@//views/index.vue'),
    children: [{
        name: 'home',
        path: '/home',
        component: () => import('/@//views/home.vue'),
    },]
}, {
    name: 'unauthorized',
    path: '/unauthorized',
    component: () => import('/@//views/unauthorized.vue'),
}]

let views = import.meta.glob('../../views/*/*.vue');

const addDynamicRoute = (name, menus) => {
    menus.forEach(item => {
        router.addRoute(name, {
            name: item.name,
            path: item.path,
            component: () => item.component === 'router' ? Router : views['../../views/' + item.component + '.vue'](),
            props: true
        });
        if (item.children && item.children.length > 0) {
            addDynamicRoute(item.name, item.children);
        }
    })
}

export const router = VueRouter.createRouter({
    history: VueRouter.createWebHistory(), routes,
});

export const beforeEach = ((to, from, next) => {
    let path = to.path;
    if (path === '/unauthorized') {
        next();
    } else if (cookie.get("access_token")) {
        if (!localStorage.getItem('menus')) {
            JSON.parse(localStorage.getItem('menus'))
        }
        if (router.hasRoute(to.name)) {
            next()
        } else {
            addDynamicRoute('index', JSON.parse(localStorage.getItem('menus')));
            next({path: to.path});
        }
    } else {
        let search = window.location.search;
        if (path === '/' && search.indexOf('code') > -1) {
            let params = qs.parse(search.substring(1, search.length));
            api.user.token({code: params.code}).then((res) => {
                if (res.access_token) {
                    const expiresIn = res.expires_in * 1000;
                    /* setTimeout(() => {

                     }, expiresIn);*/
                    let expires = new Date(new Date().getTime() + expiresIn);
                    cookie.set('access_token',
                        res.access_token, {
                            expires: expires
                        }
                    )
                    cookie.set('token_type',
                        res.token_type, {
                            expires: expires
                        }
                    )
                    cookie.set('refresh_token',
                        res.refresh_token, {
                            expires: expires
                        }
                    )
                    next({path: '/home'});
                    api.menu.getMenus().then(response => {
                        addDynamicRoute('index', response.data);
                        localStorage.setItem('menus', JSON.stringify(response.data));
                        next({path: '/home'});
                    });
                }
            });
        } else if (path === "/") {
            next({path: '/home'});
        } else {
            window.location.href = `${import.meta.env.VITE_AUTH_URL}/oauth2/authorize?response_type=code&`
                + `client_id=${import.meta.env.VITE_CLIENT_ID}&`
                + `client_secret=${import.meta.env.VITE_CLIENT_SECRET}&`
                + `redirect_uri=http://127.0.0.1`;
        }
    }
})
